<?php

class Magentochina_Bundlepromotion_Model_Bundlepromotion extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('bundlepromotion/bundlepromotion');
    }
	
	public function save()
	{
		$dundlepromotion_data = Mage::getModel('bundlepromotion/bundlepromotion')->load( $this->getData('bundlepromotion_id') );
		
		$this->setData( 'product_ids',str_replace( ' ','',$this->getData( 'product_ids' ) ) );
		
		$product_collection = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter("entity_id",array('in'=>explode( ',',$this->getData( 'product_ids' ) )));
		$models = '';
		foreach( $product_collection as $_product ){
			$models .= $_product->getData('sku').',';
		}
		$models = trim(  $models,',');
		$this->setData( 'models',$models );
		
		if( !$dundlepromotion_data->getData('rule_id') ){
			$salesule = Mage::getModel("bundlepromotion/salerule")->init($this);
			$salesule->setData('coupon_code', time());
		}else{				
			$salesule = Mage::getModel("bundlepromotion/salerule")->init($this)->load( $dundlepromotion_data->getData('rule_id') );				
		}		
		
		$salesule->save();	
		
		$this->setData('rule_id', $salesule->getData('rule_id'));
		$this->setData('coupon_code', $salesule->getData('coupon_code'));
		return parent::save();
	}
	
	public function delete()
	{		
		Mage::getModel("bundlepromotion/salerule")->load( $this->getData('rule_id') )->delete();
		return parent::delete();
	}
	
	public function getBundledPromotions( $product_id )
	{
		$dundlepromotions = Mage::getModel('bundlepromotion/bundlepromotion')->getCollection()->addFieldToFilter("product_ids",array( array('like'=>"{$product_id},%"),array('like'=>"%,{$product_id},%"), array('like'=>"%,{$product_id}") ));
		return $dundlepromotions;
	}
	
	public function getDiscount( $total_price = '' )
	{
		if( $this->getData('simple_action') == 'by_percent' ){
			return round( $this->getData('discount_amount'), 2 );
		}else if( $this->getData('simple_action') == 'by_fixed' ){
			if( $total_price > 0 ){
				return round( $this->getData('discount_amount')*100/$total_price, 2 );
			}else return 0;
		}
	}
	
	public function getProductCollection()
	{		
		return Mage::getModel('catalog/product')->getCollection()->addFieldToFilter("entity_id",array('in'=>explode( ',',$this->getData('product_ids') )))->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
			->joinField('qty',
                'cataloginventory/stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left');
	}
}